import re
import time

from tqdm import tqdm

from simple_tools import *


def main():
    is_index_sort = True
    save_file_path = "."
    while True:
        input_f: str = input("输入存放视频的文件夹的绝对路径:\n >")

        if os.path.isdir(input_f) is False:
            print("[%s] 不是有效的路径." % input_f)
            continue

        input_save_path: str = input(
            "输入存放生成结果的文件夹的绝对路径[留空将存入存放视频的文件夹(%s)]:\n >" % input_f)

        if len(input_save_path) != 0 and os.path.isdir(input_save_path) is False:
            print("[%s] 不是有效的路径." % input_save_path)
            continue

        out_file_name = "out_%d_%s.csv" % (time.time(), os.path.basename(input_f))

        if len(input_save_path) == 0:
            save_file_path = os.path.join(input_f, out_file_name)
        else:
            save_file_path = os.path.join(input_save_path, out_file_name)

        is_index_sort = True if input("是否启用序号字符串优化? \n"
                                      " * 序号字符串优化将令文件名首的数字字符按照数字处理, 而不是字符处理; \n"
                                      " * 每个最小子文件夹将独立排序;\n"
                                      " * 如果不了解这个选项, 请按回车.(Y/n)\n   >") not in ['n', 'N', 'no'] else False
        if is_index_sort:
            print("[序号字符串优化]处于启用状态.")
        else:
            print("[序号字符串优化]处于关闭状态.")

        if input("输出文件将位于[%s]. 立即处理? (Y/N)\n >" % save_file_path) in ['y', 'Y', 'yes']:
            break

    file_name_list: list = find_files_with_extension(input_f, "mp4", is_index_sort=is_index_sort)

    file_duration_list = [get_video_duration(t) for t in tqdm(file_name_list, desc="处理中...")]

    sum_duration = sum(file_duration_list)

    step_sum = 0

    with open(save_file_path, "w+", encoding="gbk") as f:
        f.write("index, filename, duration, percent, cumulative\n")
        for i, (file_name, duration) in enumerate(zip(file_name_list, file_duration_list)):
            step_sum += duration
            f.write("%03d, %s, %d, %.5f, %.5f\n" % (
                i + 1, os.path.basename(file_name), duration, (duration / sum_duration), (step_sum / sum_duration)))
    print("完成.")


if __name__ == '__main__':
    main()
